﻿using Abp.Threading;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzNetJob
{
    public class QuartzHelperT
    {
        // 存储Job的队列 可视化可以用 
        public Dictionary<string, ScheduledTaskBase> QuartzList = new();
        private readonly IScheduler scheduler;
        public QuartzHelperT()
        {
            StdSchedulerFactory factory = new();
            scheduler = factory.GetScheduler().Result;
            scheduler.Start().Wait();
        }
        public string SetDelayJob<T>(DateTimeOffset delay,object data) where T : ScheduledTaskBase
        {
            ScheduledTaskBase Job = Activator.CreateInstance<T>();
            string JobKey = Guid.NewGuid().ToString();
            IDictionary<string, object> jbData = new Dictionary<string, object>
            {
                { JobKey, Job }
            };
            IJobDetail job1 = JobBuilder.Create<JobInstance>()
           .WithIdentity(JobKey)
           .SetJobData(new JobDataMap(jbData)).Build();
            ITrigger trigger = TriggerBuilder.Create()
              .WithIdentity(JobKey)
              .StartAt(delay)
              .Build();
            trigger.JobDataMap.Add("Data", data);
            AsyncHelper.RunSync(() => scheduler.ScheduleJob(job1, trigger));
            QuartzList.Add(JobKey, Job);
            return JobKey;
        }
        private class JobInstance : IJob
        {
            public async Task Execute(IJobExecutionContext context)
            {
                IDictionary<string, object> jobs = context.JobDetail.JobDataMap;
                if (jobs != null)
                {
#pragma warning disable CS8600 // 将 null 字面量或可能为 null 的值转换为非 null 类型。
                    ScheduledTaskBase jobObj = jobs.Values.FirstOrDefault() as ScheduledTaskBase;
#pragma warning restore CS8600 // 将 null 字面量或可能为 null 的值转换为非 null 类型。
#pragma warning disable CS8602 // 解引用可能出现空引用。
                    await jobObj.RunAsync(context);
#pragma warning restore CS8602 // 解引用可能出现空引用。
                }
            }
        }
    }
}
